package com.itheima.reggie.common;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * springmvc 提供的拦截器
 * 1. 编写一个类，实现HandlerInterceptor
 * 2. 配置拦截器，拦截路径/*
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //判断用户是否登录（看session中有没有employee），如果登录就放行
        Object employee = request.getSession().getAttribute("employee");
        Object user = request.getSession().getAttribute("user");



        log.warn("访问者ip地址： {}",request.getRemoteAddr());
        if (employee != null) {
            //        Thread.currentThread().setName(employee.toString());
            BaseContext.setCurrentId((Long)employee);
            return true;
        }
        if (user != null) {
            BaseContext.setCurrentId((Long)user);
            return true;
        }
        //TODO 本地访问配置 限制ip
//        if(!(request.getRemoteAddr().equals("localhost")
//                ||request.getRemoteAddr().equals("192.168.140.1")
//                ||request.getRemoteAddr().equals("0:0:0:0:0:0:0:1"))){
//            return true;
//        }
        //表示用户没有登录，告诉前端，本次请求访问未登录，被拒接处理，响应code=0，msg=NOTLOGIN
        String json = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(json);

        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //释放资源
        BaseContext.removeCurrentId();
    }
}
